package com.hp.shiro.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.hp.shiro.bean.Result;
import com.hp.shiro.model.MenuInfo;
import com.hp.shiro.model.RoleInfo;
import com.hp.shiro.model.UserInfo;
import com.hp.shiro.repository.UserRepository;

/**
 * @Description:用户服务类
 * @author hp
 * @date 2018年5月20日 上午9:15:59
 */
@Service
public class UserService {

	@Autowired
	private UserRepository userRep;
		
	@Autowired
	private MenuService menuService;
	
	@Cacheable("userInfoCache")
	public UserInfo queryUser(String account){
		
		UserInfo user = userRep.findByAccount(account);
		
		Map<Long,MenuInfo> map = new HashMap<Long,MenuInfo>();
		
		//用户可以能有多个角色 ， 包含有相同菜单权限，要去重后组装成tree排序
		user.getRoleList().forEach(role->{
			role.getMenuList().forEach(meun->{
				map.put(meun.getId(), meun);
			});
		});
		List<MenuInfo> menuList = new ArrayList<MenuInfo>();
		if(!StringUtils.isEmpty(map)){
			for(Long key : map.keySet()){
				MenuInfo m = map.get(key);
				menuList.add(m);
			}
			user.setMenuList(menuService.treeMenu(menuList));
		}
		return user;
	}

	public List<UserInfo> findByDepartment(String depCode) {
		List<String> depList = Arrays.asList(depCode.split(","));
		return userRep.findByDepartmentCodeIn(depList);
	}


	public UserInfo findById(Long id) {
		return userRep.findById(id).get();
	}


	public Result saveUser(Long userId, String userName, String roleStr) {
		try {
			UserInfo u = new UserInfo();
			if(0!=userId){
				u = userRep.findById(userId).get();
			}
			u.setRealName(userName);
			List<RoleInfo> roleList = new ArrayList<RoleInfo>();
			Arrays.asList(roleStr.split(",")).forEach(action->{
				RoleInfo r = new RoleInfo();
				r.setId(Long.parseLong(action));
				roleList.add(r);
			});
			u.setRoleList(roleList);
			userRep.save(u);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.fail(e.getMessage());
		}
		return Result.success();
	}


	public Result saveUser(UserInfo user) {
		try {
			userRep.save(user);
		} catch (Exception e) {
			Result.fail(e.getMessage());
		}
		return Result.success();
	}

	public UserInfo findByAccount(String account) {
		return userRep.findByAccount(account);
	}
	
} 
